﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Components;

namespace UDS.SubModule.StaffPages
{
    /// <summary>
    /// ModifyInfo 的摘要说明。
    /// </summary>
    [Obsolete("Need to remove this page!")]
    public partial class ModifyInfo1Page : Page
    {
        protected static bool displaytype;

        #region helper methods used in aspx code

        protected static string GetSex(string sex, string id)
        {
            if (id != "")
                return ((sex == "True") ? "女" : "男");
            return ("");
        }

        protected static string GetAge(string birthday)
        {
            if ((birthday != "") && (DateTime.Parse(birthday) != DateTime.Parse("1900-1-1")))
                return ((DateTime.Now.Year - (DateTime.Parse(birthday)).Year + 1).ToString());
            return ("");
        }

        protected static int GetSexList(string sex, string id)
        {
            if (id != "")
            {
                return ((sex == "True") ? 1 : 0);
            }
            return (0);
        }

        #endregion helper methods used in aspx code

        protected override void OnInit(EventArgs e)
        {
            StaffList.EditCommand += StaffList_EditCommand;
            StaffList.UpdateCommand += StaffList_UpdateCommand_1;
            txb_ItemPerPage.TextChanged += txb_ItemPerPage_TextChanged;
            btn_first.Click += PagerButtonClick;
            btn_pre.Click += PagerButtonClick;
            btn_next.Click += PagerButtonClick;
            btn_last.Click += PagerButtonClick;
            btn_Go.ServerClick += btnGo_Click;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                displaytype = (Request.Params["displayType"] == null) ? false : (Request.Params["displayType"] == "0") ? false : true;
                BindGrid();
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        [Obsolete("Call Staff.GetAllStaff instead of run sproc_GetAllStaff")]
        private void BindGrid()
        {
            var db = new Database();
            var prams = new[]
            {
                Database.MakeInParam("@StaffType", SqlDbType.Bit, 1, displaytype)
            };
            DataTable dt;
            using (SqlDataReader dr = db.RunDataReader("dbo.sproc_GetAllStaff", prams))
            {
                dt = Tools.ConvertDataReaderToDataTable(dr);
            }

            //在DataTable的末尾加上空行，使得DataGrid固定行数
            int blankrows = StaffList.PageSize - (dt.Rows.Count % StaffList.PageSize);
            for (int i = 0; i < blankrows; i++)
            {
                dt.Rows.Add(dt.NewRow());
            }

            StaffList.DataSource = dt.DefaultView;
            StaffList.DataBind();


            //对于空纪录不显示checkbox
            for (int i = 0; i < StaffList.Items.Count; i++)
            {
                if (StaffList.Items[i].Cells[1].Text == "&nbsp;")
                {
                    StaffList.Items[i].FindControl("cb_StaffID").Visible = false;
                }
            }
            lbl_totalrecord.Text = StaffList.PageCount.ToString();
            lbl_curpage.Text = txb_PageNo.Text = (StaffList.CurrentPageIndex + 1).ToString();
            txb_ItemPerPage.Text = StaffList.PageSize.ToString();
            lbl_totalpage.Text = StaffList.PageCount.ToString();
        }


        private void PagerButtonClick(object sender, ImageClickEventArgs e)
        {
            //获得LinkButton的参数值
            String arg = ((ImageButton)sender).CommandArgument;

            switch (arg)
            {
                case ("next"):
                    if (StaffList.CurrentPageIndex < (StaffList.PageCount - 1))
                    {
                        StaffList.CurrentPageIndex++;
                    }
                    break;
                case ("pre"):
                    if (StaffList.CurrentPageIndex > 0)
                    {
                        StaffList.CurrentPageIndex--;
                    }
                    break;
                case ("first"):
                    StaffList.CurrentPageIndex = 0;
                    break;
                case ("last"):
                    StaffList.CurrentPageIndex = (StaffList.PageCount - 1);
                    break;
                default:
                    //本页值
                    StaffList.CurrentPageIndex = Convert.ToInt32(arg);
                    break;
            }
            BindGrid();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            //页面直接跳转的代码
            if (txb_PageNo.Text.Trim() != "")
            {
                int PageI = Int32.Parse(txb_PageNo.Text.Trim()) - 1;
                if (PageI >= 0 && PageI < (StaffList.PageCount))
                {
                    StaffList.CurrentPageIndex = PageI;
                }
            }
            BindGrid();
        }


        private void txb_ItemPerPage_TextChanged(object sender, EventArgs e)
        {
            if (txb_ItemPerPage.Text.Trim() != "")
            {
                int itemPage = Int32.Parse(txb_ItemPerPage.Text.Trim());
                if (itemPage > 0)
                {
                    StaffList.PageSize = Int32.Parse(txb_ItemPerPage.Text.Trim());
                }
            }
            BindGrid();
        }

#if false
        private string GetSelectedItemID(string controlID)
        {
            string selectedID = "";
            //遍历DataGrid获得checked的ID
            foreach (DataGridItem item in StaffList.Items)
            {
                if (((CheckBox) item.FindControl(controlID)).Checked)
                {
                    selectedID += item.Cells[1].Text.Trim() + ",";
                }
            }
            selectedID = selectedID.Substring(0, selectedID.Length - 1);
            return selectedID;
        }

        private void cmdChangeDepartment_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("../Department/ChangeDepartment.aspx?BackFilePath=" + Request.CurrentExecutionFilePath + "&StaffIDS=" + GetSelectedItemID("cb_StaffID"));
        }

        private void cmdRestoreDocument_ServerClick(object sender, EventArgs e)
        {
            var st = new Components.Staff();
            if (st.ReturnPosition(GetSelectedItemID("cb_StaffID")) == false)
            {
                Server.Transfer("../Error.aspx");
            }
            else
            {
                Response.Redirect("Rehab.aspx");
            }
        }
#endif

        private void StaffList_EditCommand(object source, DataGridCommandEventArgs e)
        {
            StaffList.EditItemIndex = e.Item.ItemIndex;
            BindGrid();

            //造出当前行内的DropDownList

            var department = (DropDownList)StaffList.Items[StaffList.EditItemIndex].FindControl("department");
            var db = new Database();

            try
            {
                using (var dr = db.RunDataReader("dbo.sproc_GetAllDepartment"))
                {
                    department.DataSource = dr;
                    department.DataTextField = "Department_Name";
                    department.DataValueField = "Department_ID";

                    department.DataBind();
                }

                foreach (ListItem lt in department.Items)
                {
                    if (lt.Value == StaffList.Items[e.Item.ItemIndex].Cells[8].Text)
                    {
                        lt.Selected = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
                Server.Transfer("../Error.aspx");
            }
        }


        private void StaffList_UpdateCommand_1(object source, DataGridCommandEventArgs e)
        {
            var db = new Database();
            var prams = new[] {
                Database.MakeInParam("@Staff_ID", SqlDbType.Int, 4, Int32.Parse(e.Item.Cells[0].Text)),
                Database.MakeInParam("@RealName", SqlDbType.NVarChar, 50, ((TextBox) e.Item.Cells[1].Controls[1]).Text),
                Database.MakeInParam("@Mobile", SqlDbType.NVarChar, 50, ((TextBox) e.Item.Cells[2].Controls[1]).Text),
                Database.MakeInParam("@Sex", SqlDbType.Bit, 1, Convert.ToBoolean(((DropDownList) e.Item.Cells[4].Controls[1]).SelectedItem.Value)),
                Database.MakeInParam("@Email", SqlDbType.NVarChar, 500, ((TextBox) e.Item.Cells[5].Controls[1]).Text),
                Database.MakeInParam("@Department_ID", SqlDbType.Int, 4, Int32.Parse(((DropDownList) e.Item.Cells[6].Controls[1]).SelectedItem.Value))
            };
            try
            {
                db.RunProc("dbo.sproc_UpdateStaffInfo", prams);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
                Server.Transfer("../Error.aspx");
            }
        }
    }
}